const column = require('../models/column')
const article = require('../models/article')
const fun = require('./utils')

let addData = (body, res) => {
	fun.add(article, body, res)
}
let getPage = async (body, res) => {
	let currentPage = parseInt(body.currentPage) || 1
	let pageSize = parseInt(body.pageSize) || 10
	let columnName = body.columnName
	let where = {}
	// 如果有栏目名参数
	columnName ? where['cname'] = columnName : null
	let arr = ['title']
	for (let i in body) {
		arr.forEach(item => {
			if (body[i] !== '' && i === item) {
				where[i] = body[i]
			}
		})
	}
	let order = []
	if (body.sort && body.order) {
		order = [[body.sort, body.order]]
	}
	await article.findAndCountAll({
		where: where,
		offset: (currentPage - 1) * pageSize,
		limit: pageSize,
		order: order
	}).then(async result => {
		let arr = result.rows
		// for (let i = 0; i < arr.length; i++) {
		// 	await column.findOne({
		// 		where: { id: arr[i].cid },
		// 		raw: true
		// 	}).then(result => {
		// 		arr[i]['dataValues']['cname'] = result.name
		// 	})
		// }
		res.json({
			code: 0,
			data: {
				currPage: currentPage,
				list: arr,
				pageSize: pageSize,
				totalCount: result.count,
				totalPage: Math.ceil(
				  result.count / pageSize
				)
			},
			msg: 'success'
		})
	})
}
let getList = (body, res) => {
	fun.list(article, body, res)
}
let getInfo = async (body, res) => {
	fun.info(article, body, res)
	let params = {
		where: { id: body.id }
	}
	const detail = await article.findOne(params)
	// 浏览量加一
	body.views = detail.views += 1
	// 更新浏览量
	await article.update(body, params)
}
let updateData = (body, res) => {
	fun.update(article, body, res)
}
let deleteData = (body, res) => {
	fun.del(article, body, res)
}
let updateViews = async (body, res) => {
	let num = -1
	await article.findOne({
		where: { id: body.id },
		raw: true
	}).then(result => {
		num = result.views
	})
	body.views = num + 1
	await article.update(body, {
		where: { id: body.id }
	}).then(result => {
		res.json({
			code: 0,
			data: null,
			msg: 'success'
		})
	}).catch(err => {
		res.json({
			code: 500,
			data: null,
			msg: err
		})
	})
}
let getTypeSort = async (body, res) => {
	let sort = body.sort
	let order = body.order || 'desc'
	let pageSize = parseInt(body.pageSize) || 10
	let params = {
		order: [
			[sort, order]
		],
		limit: pageSize
	}
	await article.findAndCountAll(params).then(result => {
		res.json({
			code: 0,
			data: result,
			msg: 'success'
		})
	}).catch(err => {
		// resErr(res, err)
	})
}
module.exports = {
	addData,
	getPage,
	getList,
	getInfo,
	updateData,
	deleteData,
	updateViews,
	getTypeSort
}
